package com.hitalkie.teacher.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.hitalkie.teacher.R;
import com.hitalkie.teacher.app.TalkieApplication;
import com.hitalkie.teacher.fragment.LoadingDialogFragment;
import com.hitalkie.teacher.tx.MySelfInfo;
import com.hitalkie.teacher.tx.QavsdkControl;
import com.tencent.TIMCallBack;
import com.tencent.TIMManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.common.inter.ITagManager;
import com.umeng.message.tag.TagManager;

import java.util.Locale;

/**
 * Date 04/11/2016
 *
 * @author charliema
 */

public class SettingActivity extends BaseActivity {


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkSignIn();
        initView();
    }

    private void checkSignIn() {
        if (!TalkieApplication.isSignIn()) {
            Toast.makeText(getActivity(), "请先注册或登录", Toast.LENGTH_LONG).show();
            startActivity(new Intent(getActivity(), SignUpActivity.class));
            getActivity().finish();
        }
    }

    private void initView() {
        setContentView(R.layout.view_setting);
        initTitleBar();
        findViewById(R.id.tvSignOut).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signOut();
            }
        });
        findViewById(R.id.tvPasswordEdit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), PasswordEditActivity.class));
            }
        });
        findViewById(R.id.tvPhoneEdit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), PhoneEditActivity.class));
            }
        });
//        findViewById(R.id.tvWechatBind).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
        findViewById(R.id.tvChangeLanguage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                MobclickAgent.onEvent(getActivity(),"click_language");
                new AlertDialog.Builder(getActivity())
                        .setTitle("选择语言 / choose language")
                        .setItems(new String[]{"中文 / Chinese", "英文 / English"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    TalkieApplication.setLocale(Locale.CHINESE);
                                } else {
                                    TalkieApplication.setLocale(Locale.ENGLISH);
                                }
                                // 跳转到首页并且重新刷新
                                Intent i = new Intent(getActivity(), MainActivity.class);
                                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                i.putExtra("need_refresh", true);
                                startActivity(i);
                            }
                        })
                        .show();
            }
        });
        findViewById(R.id.tvAbout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent().setClass(getActivity(), AboutActivity.class));
            }
        });
        findViewById(R.id.tvCacheClear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cacheClear();
            }
        });

    }

    private void initTitleBar() {
        findViewById(R.id.viewTitleBarLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }

    private void signOut() {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        TalkieApplication.signOut();

        TIMManager.getInstance().logout(new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                Log.e(TAG, "IMLogout fail ：" + i + " msg " + s);
                Toast.makeText(getActivity(), "退出失败", Toast.LENGTH_LONG).show();
                // loading dialog
                loadingDialogFragment.dismiss();
            }

            @Override
            public void onSuccess() {
                Log.i(TAG, "IMLogout succ !");
                //清除本地缓存
                MySelfInfo.getInstance().clearCache(getApplicationContext());
                //反向初始化avsdk
                stopAVSDK();

                unbindPush();
                MobclickAgent.onProfileSignOff();

                // loading dialog
                loadingDialogFragment.dismiss();
                Intent i = new Intent(getActivity(), MainActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(i);
            }
        });


    }

    private void cacheClear() {
//        Picasso.with(getActivity()).cache.clear();
        // fake
        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getActivity(), "Clear cache done", Toast.LENGTH_SHORT).show();
            }
        }, 1000);
    }

    private void unbindPush() {
        String userId = "" + TalkieApplication.getUserId();
        // 解绑 alias
        PushAgent.getInstance(getApplicationContext()).removeAlias("" + userId, "NONE", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean b, String s) {
                Log.e(TAG, "unbind push alias:" + b + "   " + s);
            }
        });
        // 解绑tag
        PushAgent.getInstance(getApplicationContext()).getTagManager().reset(new TagManager.TCallBack() {
            @Override
            public void onMessage(boolean b, ITagManager.Result result) {
                Log.e(TAG, "unbind push tag:" + b + "   " + result);

            }
        });
        // 绑定tag 游客
        PushAgent.getInstance(getApplicationContext()).getTagManager().add(new TagManager.TCallBack() {
            @Override
            public void onMessage(boolean isSuccess, ITagManager.Result result) {
                if (isSuccess) {
                } else {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "登录失败：无法绑定推送Tag", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }, "-1");
    }


    /**
     * 反初始化AVADK
     */
    public void stopAVSDK() {
        QavsdkControl.getInstance().stopContext();
    }


}
